﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTO;
using System.IO;
using BUS;
using System.Xml;
using System.Data.SqlClient;
namespace GPBenhLanh
{
    public partial class frmKetQuaCL : DevExpress.XtraEditors.XtraForm
    {
        public frmKetQuaCL()
        {
            InitializeComponent();
        }
        TTXacNhanDTO _xn;
        public TTXacNhanDTO Xn
        {
            get { return _xn; }
            set { _xn = value; }
        }

        private TTKetQuaDTO kq = new TTKetQuaDTO();

        string _sThuMucLuu;
        public string sThuMucLuu
        {
            get { return _sThuMucLuu; }
            set { _sThuMucLuu = value; }
        }

        public static string _strConnectPK;
        SqlConnection conpk;
        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPK()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhkham");
            _strConnectPK = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public void CnPKham()
        {
            if (conpk == null || conpk.State == ConnectionState.Closed)
            {
                getConnectStringPK();
                conpk = new SqlConnection();
                conpk = Uit.it_Conn.getConnect(_strConnectPK);
            }
        }

        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        private Bitmap bmHinh3 = null;
        private Bitmap bmHinh4 = null;
        private int ketqua = 0;
        private int flagLuu = 1;
        private int flagKQ = 0;
        private int lan = 0;
        private DateTime cDate = DateTime.Today;//ngay xac nha cua ket qua
        private DateTime cDate2 = DateTime.Today;//ngay xac nha cua ket qua
      
        private int[] dataTran = new int[4];
        private static string strPathHinh = "";
        public void getPathStrHinh()
        {
            string _sConnection = Uit.it_Conn.getConnectString("pathStrHinh");
            strPathHinh = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public delegate void MyDelege2(object sender, Object data);
        public event MyDelege2 thoatEven;

        private int[] isImg= new int[4]{0,0,0,0};

        public frmKetQuaCL(TTXacNhanDTO xnf)
        {
            InitializeComponent();
            Xn = xnf;
            initControl(this);
        }

        private void initControl(Control ctrl)
        {

            // Bỏ qua điều kiểm trừ khi nó là TextBox.
            if (ctrl.Tag == "text")
            {
                ctrl.Text = "";
            }

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control ctrlChild in ctrl.Controls)
            {
                initControl(ctrlChild);
            }
        }

        private void loadTTHC()
        {
            //set thong tin hanh chinh cua benh nha
            txtHoTen.Text = Xn.HoTen;
            int Tuoi = DateTime.Today.Year - Convert.ToInt32(Xn.NamSinh);
            txtTuoi.Text = Xn.NamSinh.ToString();
            if (Xn.Gioi == true)
                txtGioi.Text = "Nam";
            else
                txtGioi.Text = "Nữ";
        
            txtSoHS.Text = Xn.SoHS;
            txtSoBN.Text = Xn.SoBN;
            txtDichVu.Text = Xn.TenDVu;
            txtSoNVien.Text = Xn.SoNV;
            txtDVChiDinh.Text = Xn.TenDViChiDinh;
            txtChuanDoan.Text = Xn.ChuanDoan;
            DataTable dtbs = GetThongTinSearchBUS.SearchDSBacSi();
            
            comBacSi.Properties.DataSource = dtbs;
          
            comKTV.Properties.DataSource = GetThongTinSearchBUS.SearchDSKTV();           
       
            combscd.Properties.DataSource = GetThongTinSearchBUS.SearchDSBacSiCD();
            combscd.EditValue = Xn.PTVien;
            txtPTV.Text = combscd.Text;

            comPPMo.Properties.DataSource = GetThongTinSearchBUS.SearchPPMo();
            comPPMo.EditValue = Xn.PPMo;
            txtPPMo.Text = comPPMo.Text;
            txtDienThoai.Text = Xn.DienThoai;
            lblLoaiBN.Text = Xn.LoaiBN.ToString();
            lblDVCode.Text = Xn.DVuCode;

            //add 27.01.2015
            DataTable dtPPNhuom = new DataTable();
            dtPPNhuom = GetThongTinSearchBUS.GetDSPPNhuom();
            comPPNhuom.Properties.DataSource = dtPPNhuom;
            comPPNhuom.Properties.DisplayMember = "TenPPNhuom";
            comPPNhuom.Properties.ValueMember = "IDPPNhuom";
            // Specify the separator character.
            comPPNhuom.Properties.SeparatorChar = ';';
            //setdefaut value pp Nhuom is H&E
            comPPNhuom.SetEditValue(1);
            // Disable the H&E item.
            comPPNhuom.Properties.Items[0].Enabled = false;

            DataTable dtNgCat = GetThongTinSearchBUS.SearchDSNguoiCatLoc();
            comNguoiCatLoc.Properties.DataSource = dtNgCat;

            datNgayCatLoc.DateTime = DateTime.Now.Date;
            datNgayLenLam.DateTime = DateTime.Now.Date;
            //end add
        }

        public string Right(string value, int length)
        {
            return value.Substring(value.Length - length);
        }
        int soFS = 0;
              
        private void loadKQ()
        {
            //load lai kq
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,Xn.SoTieuBan,1);          
            if (dt.Rows.Count > 0)
            {
                comBacSi.EditValue = int.Parse(dt.Rows[0]["IDBacSiTH"].ToString());
                combscd.EditValue = Xn.IDBacSiCD;
                comKTV.EditValue = int.Parse(dt.Rows[0]["IDKTV"].ToString());
                txtsotieuban.Text = dt.Rows[0]["SoTieuBan"].ToString();
                txtsotieuban.Enabled = false;
                
                //neu da co ket qua
                if (dt.Rows[0]["KQViThe"].ToString() != "")
                {
                    pnlKQ.Enabled = false;                   
                    btnLuuKetQua.Enabled = false;

                    txtDaiThe1.Text     = dt.Rows[0]["KQDaiThe"].ToString();
                    txtViThe1.Text = dt.Rows[0]["KQViThe"].ToString();
                    txtKetLuan1.Text    = dt.Rows[0]["KetLuan"].ToString();
                    lan = 1;
                    isImg[0] = 1;
                    Xn.KQ1 = txtsotieuban.Text;
                    //add 27.01.2015
                    if (dt.Rows[0]["IDNguoiCat"].ToString() != "")
                        comNguoiCatLoc.EditValue = int.Parse(dt.Rows[0]["IDNguoiCat"].ToString());
                    else
                        comNguoiCatLoc.EditValue = 0;

                    if (dt.Rows[0]["SoLam"].ToString() != "")
                        txtSlgLam.Text = dt.Rows[0]["SoLam"].ToString();
                    else
                        txtSlgLam.Text = "0";
                    
                    if (dt.Rows[0]["NgayCat"].ToString() != "")
                        datNgayCatLoc.EditValue = Convert.ToDateTime(dt.Rows[0]["NgayCat"].ToString());
                    else
                        datNgayCatLoc.DateTime = DateTime.Now.Date.AddDays(-1);
                
                    if (dt.Rows[0]["NgayLenLam"].ToString() != "")
                        datNgayLenLam.EditValue = Convert.ToDateTime(dt.Rows[0]["NgayLenLam"].ToString());
                    else
                        datNgayLenLam.DateTime = DateTime.Now.Date;

                    if (dt.Rows[0]["IDPPNhuom"].ToString() != "")
                        comPPNhuom.SetEditValue(dt.Rows[0]["IDPPNhuom"].ToString());
                    else
                        comPPNhuom.SetEditValue(1);

                    if (dt.Rows[0]["SlgMauCat"].ToString() != "")
                    {
                        txtSlgMauCat.Text = dt.Rows[0]["SlgMauCat"].ToString();
                    }
                    else
                        txtSlgMauCat.Text = "1";
                    //end add
                }
                else
                {
                    btnSuaKQ.Enabled = false;
                }
            }
            else//neu chua co ket qua
            {
                lan = 1;
                txtDaiThe1.Text = "";
                txtViThe1.Text = "";
                txtKetLuan1.Text = "";
                btnLuuKetQua.Enabled = true;
                btnSuaKQ.Enabled = false;
                //set so tieu ban FSyy-XXXX
                txtsotieuban.Text = Xn.SoTieuBan;

                //add 27.01.2015
                txtSlgLam.Text = "1";
                txtSlgMauCat.Text = "1";                
                //end add
            }           
        }

        private void setDataToForm()
        {
            //load lai thong tin hanh chinh cua benh nhan
            loadTTHC();
            //load lai ket qua cho benh nhan
            loadKQ();           
        }
       
        private void LoadHinh(PictureEdit edit, ref Bitmap bm)
        {
            edit.Image = bm;
        }
        
        string path = "";
        private void LoadLaiHinhKQ(string lanthu, PictureEdit pic1, PictureEdit pic2
                                    , ref Bitmap Hinh1, ref Bitmap Hinh2)
        {
            
            string pathTemp_x100 = Application.StartupPath + "\\PictureTemp" +
                                    "\\x100_" + lanthu.ToString() + "_1.jpg";
            //x100
            if (File.Exists(pathTemp_x100))
            {
                if (!File.Exists(sThuMucLuu + "\\x100_" + lanthu.ToString() + "_1.jpg"))
                {
                    File.Copy(pathTemp_x100, sThuMucLuu  + "\\x100_" + lanthu.ToString() + "_1.jpg");
                }
            }

            string pathHinhDaLuu_x100 = sThuMucLuu + "\\"  + "\\x100_" + lanthu.ToString() + "_1.jpg";
            if (File.Exists(pathHinhDaLuu_x100))
            {
                //doc file
                Stream stream = File.Open(pathHinhDaLuu_x100, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();

                Hinh1 = m_Bitmap;
                LoadHinh(pic1, ref Hinh1);
            }
            //x400
            string pathTemp_x400 = Application.StartupPath + "\\PictureTemp" + "\\" + "\\x400_" + lanthu.ToString() + "_1.jpg";
            if (File.Exists(pathTemp_x400))
            {
                if (!File.Exists(sThuMucLuu + "\\" +  "\\x400_" + lanthu.ToString() + "_1.jpg"))
                {
                    File.Copy(pathTemp_x400, sThuMucLuu + "\\" +  "\\x400_" + lanthu.ToString() + "_1.jpg");
                }
            }

            string pathHinhDaLuu_x400 = sThuMucLuu + "\\" +  "\\x400_" + lanthu.ToString() + "_1.jpg";
            if (File.Exists(pathHinhDaLuu_x400))
            {
                Stream stream = File.Open(pathHinhDaLuu_x400, FileMode.Open,
                    FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh2 = m_Bitmap;
                LoadHinh(pic2, ref Hinh2);
            }
        }
        
        private void LoadHinh()
        {
            //load lai hinh kq
            LoadLaiHinhKQ(txtsotieuban.Text, picCL1, picCL2, ref bmHinh1, ref bmHinh2);                     
        }
         
        private void frmKetQua_Load(object sender, EventArgs e)
        {
            try
            {
                CnPKham();
                getPathStrHinh();
                setDataToForm();
                CreateDir();
                LoadHinh();
                if (txtKetLuan1.Text != "")
                    flagKQ = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }            
        } 

        void frm_thoatEven(object sender, object data)
        {
            LoadHinh();
            isImg = (int[])data;
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmChupHinh_AF frmHinh = new frmChupHinh_AF(Xn.SoTieuBan, 1);
               
                frmHinh.sThuMucLuu = strPathHinh;
                frmHinh.thoatEven += new frmChupHinh_AF.DelegeChupH(frm_thoatEven);
                frmHinh.sophieu = Xn.SoBN;
                frmHinh.DVuCode = Xn.DVuCode;         
                ClearHinh(ref picCL1, ref bmHinh1);
                ClearHinh(ref picCL2, ref bmHinh2);              
                frmHinh.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void ClearHinh(ref PictureEdit pic, ref Bitmap hinh)
        {
            if (hinh != null)
            {
                hinh.Dispose();
                hinh = null;
                pic.Image = null;
                pic.Refresh();                
            }            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    DialogResult result = MessageBox.Show("Bạn Chưa lưu kết quả./n" +
                        " Bạn có muốn lưu kết quả không ?", "Thông báo", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        btnLuuKetQua_Click(sender, e);
                    }
                }
                ClearHinh(ref picCL1,ref bmHinh1);
                ClearHinh(ref picCL2, ref bmHinh2);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }          
        }

        private void CreateDir()
        {
            string goc = strPathHinh;
            DateTime dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4);
        }

        private bool CheckSave()
        {  
            if (txtViThe1.Text == "")
            {
                ErrorProvider.SetError(txtViThe1, "Bạn phải nhập thông tin cho mô tả đại thể!");
                return false;
            }
            else
                ErrorProvider.ClearErrors();            
                    
            return true;
        }

        private List<string> GetChecked()
        {
            List<string> check = new List<string>();
            string checkedString = Convert.ToString(comPPNhuom.Properties.GetCheckedItems());
            if ((checkedString.Length > 0))
            {
                check.AddRange(checkedString.Split(new char[] { ';' }));
            }
            return check;
        }

        private string GetStringChecked()
        {
            string checkedString = Convert.ToString(comPPNhuom.Properties.GetCheckedItems());

            return checkedString;
        }

        private void btnLuuKetQua_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckSave())
                {
                    this.ketqua = 1;
                    //kiem tra ket qua truoc khi luu
                    //set value ket qua                
                    kq.SoBN = Xn.SoBN;
                    kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                    kq.IDKTV = int.Parse(comKTV.EditValue.ToString());
                    kq.CDate = DateTime.Today;
                    kq.SoTBan = txtsotieuban.Text;
                    Boolean rs = false;
                    kq.LoaiKQ = hensu.FS;
                    kq.KQDaiThe1 = txtDaiThe1.Text;
                    kq.KQViThe1 = txtViThe1.Text;
                    kq.KetLuan1 = txtKetLuan1.Text;
                    kq.UrlHinh1 = path;
                    kq.Host = Uit.it_Computer.ComputerName().ToString();
                    kq.UserName = UserDTO.LoginName.ToString();
                    kq.Lan = 1;
                    //add 27.01.2015
                    kq.SoLam = Convert.ToInt32(txtSlgLam.Text);
                    if (comNguoiCatLoc.EditValue.ToString() == "")
                    {
                        kq.IDNguoiCat = 0;
                        return;
                    }
                    else
                        kq.IDNguoiCat = int.Parse(comNguoiCatLoc.EditValue.ToString());

                    kq.NgayCat = (DateTime)datNgayCatLoc.EditValue;
                    kq.NgayLenLam = (DateTime)datNgayLenLam.EditValue;
                    kq.IDPPNhuom = GetStringChecked();
                   
                    //end add
                    rs = KQBUS.InsertKetQua(kq);

                    if (rs)
                    {
                        rs = false;
                        rs = KQBUS.UpdateXacNhan(kq.SoBN, kq.SoTBan, lan);

                KQBUS.UpdateFee(kq.SoBN, txtSoHS.Text, txtSoNVien.Text, true
                           , int.Parse(lblLoaiBN.Text), lblDVCode.Text, conpk);
                        if (rs)
                        {
                            dataTran[0] = lan;
                            if (lan >= 1)
                                dataTran[1] = 1;
                            btnLuuKetQua.Enabled = false;
                            btnSuaKQ.Enabled = true;
                            pnlKQ.Enabled = false;
                            txtsotieuban.Enabled = false;
                            //cap nhat lai so FS max                       
                            int nam = int.Parse(Right(DateTime.Today.Year.ToString(), 2));
                            int thang = DateTime.Today.Month;
                            int max = int.Parse(Right(txtsotieuban.Text, hensu.LengSoCatLanh));

                            MessageBox.Show("Lưu Thành Công", "Thông Báo");
                            flagLuu = 1;
                            flagKQ = 1;
                        }                       
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }           
        }

        private void btnInKQ_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    XtraMessageBox.Show("Chưa có kết quả!", "Thông báo");
                }
                else if (flagLuu == 1)
                {
                    rptPhieuKQ rptKQ = new rptPhieuKQ();
                    SerDataToReport(rptKQ);
                    rptKQ.Print();
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("Chưa lưu kết quả!", "Thông báo");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private int SerDataToReport(rptPhieuKQ rptKQ)
        {
            DateTime cdate = DateTime.Today, cdate2 = DateTime.Today;
            DataTable dt = KQBUS.GetKetQua(txtSoBN.Text,txtSoHS.Text,txtsotieuban.Text,1);
            if (dt.Rows.Count > 0)
            {                
                rptKQ.txtSoTieuBan.Text = dt.Rows[0]["SoTieuBan"].ToString();
                rptKQ.txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString();
                rptKQ.txtdaithe.Text = dt.Rows[0]["KQDaiThe"].ToString();
                rptKQ.txtVithe.Text = dt.Rows[0]["KQViThe"].ToString();
                if (dt.Rows[0]["KetLuan"].ToString() != "")
                {
                    rptKQ.txtketluan.Text = dt.Rows[0]["KetLuan"].ToString().ToUpper();
                }
                else
                {
                    rptKQ.lblketluan.Visible = false;
                }
                rptKQ.txtchatBP.Text = Uit.it_Font.VNIToUnicode( dt.Rows[0]["ChatBP"].ToString());
                //add 25.01.2015
                rptKQ.txtPPNhuom.Text = comPPNhuom.Text;
                rptKQ.txtNguoiCatLoc.Text = comNguoiCatLoc.Text;
                if (dt.Rows[0]["NgayCat"].ToString() != "")
                    rptKQ.txtNgayCat.Text = Convert.ToDateTime(dt.Rows[0]["NgayCat"].ToString()).ToString("dd/MM/yyyy");
                else
                    rptKQ.txtNgayCat.Text = "";

                rptKQ.txtNguoiLamTB.Text = comKTV.Text;
                if (dt.Rows[0]["NgayLenLam"].ToString() != "")
                    rptKQ.txtNgayLam.Text = Convert.ToDateTime(dt.Rows[0]["NgayLenLam"].ToString()).ToString("dd/MM/yyyy");
                else
                    rptKQ.txtNgayLam.Text = "";

                if (dt.Rows[0]["SlgMauCat"].ToString() != "")
                    rptKQ.txtSoMau.Text = dt.Rows[0]["SlgMauCat"].ToString();
                else
                    rptKQ.txtSoMau.Text = "";

                if (dt.Rows[0]["SlgMau"].ToString() != "")
                    rptKQ.txtSLgMauGui.Text = dt.Rows[0]["SlgMau"].ToString();
                else
                    rptKQ.txtSLgMauGui.Text = "";

                if (dt.Rows[0]["SoLamHM"].ToString() != "" && int.Parse(dt.Rows[0]["SoLamHM"].ToString()) != 0)
                    rptKQ.txtGhiChu.Text = dt.Rows[0]["SoLamHM"].ToString() + " tiêu bản HMMD. " + dt.Rows[0]["GhiChu"].ToString();
                else
                    rptKQ.txtGhiChu.Text = "";
                rptKQ.txtSoLam.Text = dt.Rows[0]["SoLam"].ToString();
                rptKQ.txtThuKy.Text = UserDTO.Name;
                //end add
            }
            else
            {
                return 1;
            }
            string url = "";
            string gioi = "";
            if (Xn.Gioi)
                gioi = "Nam";
            else
                gioi = "Nữ";
            
            rptKQ.barSoHS.Text = Xn.SoHS;
            rptKQ.txtSoBN.Text = Xn.SoBN;
            rptKQ.txtTraiBenh.Text = Xn.TenDViChiDinh;
            
            rptKQ.txthoten.Text = Xn.HoTen.ToUpper();
            rptKQ.txtGioiTinh.Text = gioi;
            rptKQ.txttuoi.Text = Xn.NamSinh.ToString()
                                + "(" + Xn.Tuoi.ToString() + " Tuổi)";
            rptKQ.txtnghe.Text = Xn.Nghe;
            rptKQ.txtchuandoan.Text = Xn.ChuanDoan;
            rptKQ.txtngaylaymau.Text = Xn.NgayLayMau.ToString("dd/MM/yyyy");
            rptKQ.txtptv.Text = combscd.Text;
            rptKQ.txtppmo.Text = txtPPMo.Text;

            rptKQ.txtngaynhanmau.Text = Xn.NgayNhan.ToString("dd/MM/yyyy, hh:mm");
           
            if(txtViThe1.Text =="")
            {
                return 1;
            }

            rptKQ.piclan1.Image = picCL1.Image;
            rptKQ.piclan2.Image = picCL2.Image;
            cdate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());

            rptKQ.txtketqualan.Text = "KẾT QUẢ CẮT LẠNH";
            rptKQ.txtngaythang.Text = "Ngày " + cdate.Day.ToString("00") +
                              " Tháng " + cdate.Month.ToString("00") +
                              " Năm " + cdate.Year.ToString("0000");
          
            if (rptKQ.piclan1.Image == null)
            {
                rptKQ.piclan1.Visible = false;
            }
            if (rptKQ.piclan2.Image == null)
            {
                rptKQ.piclan2.Visible = false;
            }
            rptKQ.txtngaygioin.Text =DateTime.Now.ToString("dd/MM/yyyy, hh:mm:ss");
            rptKQ.txtbsthuchien.Text = comBacSi.Text;
            return 0;
        }

        private void btnPrintRevew_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagLuu != 0)
                {
                    rptPhieuKQ rptKQ = new rptPhieuKQ();
                    int rs = SerDataToReport(rptKQ);
                    if (rs != 0)
                    {
                        MessageBox.Show("Bạn chưa nhập kết luận!", "Thông Báo");
                        return;
                    }
                    rptKQ.ShowPreviewDialog();                    
                }
                else
                {
                    DevExpress.LookAndFeel.UserLookAndFeel lookAndFeel = new DevExpress.LookAndFeel.UserLookAndFeel(this);
                    XtraMessageBox.Show(lookAndFeel, "Chưa lưu kết quả.\nBạn phải lưu kết quả trước");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void frmKetQua_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thoatEven != null)
            {
                thoatEven(this, dataTran);
            }
        }

        private void btnSuaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                flagLuu = 0;
             
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
                btnSuaKQ.Visible = false;
                btnCapnhat.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        /// <summary>
        /// xoa hinh kho xoa ket qua
        /// </summary>
        /// <param name="Filename">hinh ket qua lan thu i</param>
        /// <param name="loaiHinh">loai hinh x100 hay x400</param>
        private void xoaHinh(ref PictureEdit picXoa, ref Bitmap hinhXoa, string Filename, string loaiHinh)
        {
            string pathX = sThuMucLuu + "\\" +  loaiHinh + "_" + Filename + "_1" + ".jpg";           
            if (File.Exists(pathX))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa); 
                //xoa hinh
                File.Delete(pathX);
            }           
        }

        private void btnXoaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                //xoa database
                bool rs = KQBUS.DeleteKQ(txtSoBN.Text,txtsotieuban.Text);
                string Filename = txtsotieuban.Text;
                if (rs)
                {
                    //xoa hinh
                    xoaHinh(ref picCL1, ref bmHinh1, Filename, "X100");
                    xoaHinh(ref picCL2, ref bmHinh2, Filename, "X400");
                   
                    //update xac nhan
                    bool kqup = false;
                    kqup = KQBUS.UpdateXacNhan(Xn.SoBN, "0", 1);
                    if (kqup)
                    {
                        //dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
                        dataTran[0] = 0;
                        dataTran[1] = 1;
                        flagLuu = 0;
                        flagKQ = 0;
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(),"Thông Báo");
            }           
        }

        private void btnCapnhat_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckSave())
                {
                    kq.SoBN = Xn.SoBN;
                    kq.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                    kq.CDate = DateTime.Now;

                    Boolean rs = false;                  
                    kq.KQDaiThe2 = txtDaiThe1.Text;
                    kq.KQViThe2 = txtViThe1.Text;
                    kq.KetLuan2 = txtKetLuan1.Text;
                    kq.UrlHinh2 = path;
                    kq.SoTBan = txtsotieuban.Text;
                    kq.Host = Uit.it_Computer.ComputerName().ToString();
                    kq.UserName = UserDTO.LoginName.ToString();
                    kq.Lan = 1;
                    // add 23.01.2015
                    kq.SoLam = Convert.ToInt32(txtSlgLam.Text);
                    kq.SoMauCat = Convert.ToInt32(txtSlgMauCat.Text);
                    if (comNguoiCatLoc.EditValue.ToString() == "")
                    {
                        kq.IDNguoiCat = 0;
                        return;
                    }
                    else
                        kq.IDNguoiCat = int.Parse(comNguoiCatLoc.EditValue.ToString());

                    kq.NgayCat = (DateTime)datNgayCatLoc.EditValue;
                    kq.NgayLenLam = (DateTime)datNgayLenLam.EditValue;
                    kq.IDPPNhuom = GetStringChecked();
                    if (comKTV.EditValue.ToString() == "")
                    {
                        kq.IDKTV = 0;
                        return;
                    }
                    else
                        kq.IDKTV = int.Parse(comKTV.EditValue.ToString());

                    kq.SoMauCat = int.Parse(txtSlgMauCat.Text);
                    kq.GhiChu = "";
                    // end add
                    rs = KQBUS.UpdateKetQua(kq);//1: cat lanh                   

                    if (rs)
                    {   
                        btnSuaKQ.Visible = true;
                        btnCapnhat.Visible = false;
                        pnlKQ.Enabled = false;
                        MessageBox.Show("Lưu Thành Công", "Thông Báo");
                        flagLuu = 1;
                        flagKQ = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void tabKQ_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            tabKQ_SelectedPageChanged(sender,e);
        }

        private void tabKQ_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            int ss1 = 0;            
            ss1 = DateTime.Compare(cDate, DateTime.Today);
            if (ss1 < 0)//qua ngay
            {
                ptnButtonLXS.Enabled = false;
               
                btnChupHinh.Enabled = false;
                pnlKQ.Enabled = false;
            }
            else 
            {
                ptnButtonLXS.Enabled = true;
                
                btnChupHinh.Enabled = true;
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
            }
      
        }

        private void frmKetQua_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12)
            {
                btnChupHinh_Click(sender, e);
            }
        }

        private void btnXoaH1_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text, "X100");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void btnXoaH2_Click(object sender, EventArgs e)
        {
            try
            {               
                xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text, "X400");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void txtViThe1_Leave(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtViThe1_Enter(object sender, EventArgs e)
        {
            this.txtViThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtViThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Enter(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtDaiThe1_Leave(object sender, EventArgs e)
        {
            this.txtDaiThe1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtDaiThe1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Leave(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Enter(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtsotieuban_EditValueChanged(object sender, EventArgs e)
        {
            //co ket qua roi thi khong check so tieu ban
            if (txtKetLuan1.Text != "")
            {
                //get value hien tai
                string stb = txtsotieuban.Text;
                //kiem tra data co chua
                DataTable dt = new DataTable();
                dt = KQBUS.GetKetQuaSTB(txtsotieuban.Text);
                //thong bao
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("Số Tiêu bản đã tồn tại", hensu.ThongBao);
                    ptnButtonLXS.Enabled = false;
                }
                else
                {
                    ptnButtonLXS.Enabled = true;
                }
            }
        }

        private void txtViThe1_Validated(object sender, EventArgs e)
        {
            string vithe = txtViThe1.Text;
            string[] words = vithe.Split(new string[] { "\r\n\r\n", "KEÁT LUAÄN:" }
                                        , StringSplitOptions.None);
            if (words.Length == 3)
            {
                txtViThe1.Text = words[0];
                txtKetLuan1.Text = words[2].Trim();
            }
        }
    }
}